package com.cysoft.utils;

import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 * @author caiye
 */
public class StreamUtil implements Serializable{

    public static <T> boolean writeObject(List<T> list, File file) {
        T[] array = (T[])list.toArray();
        ObjectOutputStream oos = null;
        try{
            if(!file.exists()) {
                file.createNewFile();
            }
            oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(array);
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if(oos != null) {
                try {
                    oos.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
        return true;
    }

    public static <E> List<E> readList(File file) {
        E[] objects;
        // 新的用法，括号中代码可以直接关闭流
        try(ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file))) {
            objects = (E[]) inputStream.readObject();
            return Arrays.asList(objects);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
